<template>
  <div
    class="comment-reply-item"
    :class="{ deleted: reply.isDeleted }"
    :data-reply-id="reply.id"
    @dblclick.stop="handleDoubleClick"
    @click.stop="handleClick"
  >
    <div class="reply-header">
      <div class="reply-author-avatar-wrapper">
        <img
          v-if="reply.author.avatar"
          :src="reply.author.avatar"
          :alt="reply.author.name"
          class="reply-author-avatar"
        />
        <div v-else class="reply-author-avatar-placeholder">
          {{ reply.author.name.charAt(0).toUpperCase() }}
        </div>
      </div>
      <div class="reply-author-info">
        <span class="reply-author-name">{{ reply.author.name }}</span>
        <span v-if="reply.isEdited" class="reply-edited-badge">已编辑</span>
      </div>
      <div v-if="!isResolved" class="reply-actions" @dblclick.stop>
        <!-- 点赞按钮 -->
        <el-button
          v-if="!reply.isDeleted"
          size="small"
          text
          :class="{ active: userLikeType === 'like' }"
          @click.stop="handleLike"
          @dblclick.stop
        >
          <i class="i-ri-thumb-up-line"></i>
          <span v-if="reply.likeCount && reply.likeCount > 0">{{
            reply.likeCount
          }}</span>
        </el-button>
        <!-- 点踩按钮 -->
        <el-button
          v-if="!reply.isDeleted"
          size="small"
          text
          :class="{ active: userLikeType === 'dislike' }"
          @click.stop="handleDislike"
          @dblclick.stop
        >
          <i class="i-ri-thumb-down-line"></i>
          <span v-if="reply.dislikeCount && reply.dislikeCount > 0">{{
            reply.dislikeCount
          }}</span>
        </el-button>
        <!-- 回复按钮 -->
        <el-button
          v-if="!reply.isDeleted"
          size="small"
          text
          @click.stop="handleReply"
          @dblclick.stop
        >
          回复
        </el-button>
        <!-- 更多操作菜单 -->
        <el-dropdown
          v-if="!reply.isDeleted"
          trigger="click"
          @command="handleCommand"
        >
          <el-button size="small" text @click.stop @dblclick.stop>
            <i class="i-ri-more-line"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-if="canEdit" command="edit" :icon="Edit">
                编辑
              </el-dropdown-item>
              <el-dropdown-item
                v-if="canDelete"
                command="delete"
                :icon="Delete"
                divided
              >
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 编辑模式 -->
    <div v-if="isEditing" class="reply-edit-mode">
      <el-input
        v-model="editContent"
        type="textarea"
        :rows="3"
        placeholder="编辑回复..."
        @keydown.ctrl.enter="handleSaveEdit"
        @keydown.meta.enter="handleSaveEdit"
      />
      <div class="edit-actions">
        <el-button size="small" @click="handleCancelEdit">取消</el-button>
        <el-button size="small" type="primary" @click="handleSaveEdit">
          保存
        </el-button>
      </div>
    </div>

    <!-- 正常显示模式 -->
    <div v-else class="reply-content-wrapper">
      <!-- 引用回复 - 在评论内容上方显示 -->
      <div
        v-if="reply.quote"
        class="reply-quote-inline"
        @click.stop="handleQuoteClick"
        :title="getPlainText(reply.quote.content)"
      >
        <span class="quote-content">{{
          getPlainText(reply.quote.content)
        }}</span>
      </div>
      <div v-if="reply.isDeleted" class="reply-content-deleted">
        此回复已删除
      </div>
      <div v-else class="reply-content" v-html="reply.content"></div>
      <!-- 时间显示在评论内容最下方 -->
      <div class="reply-time-meta">
        <span class="reply-time">{{ formatTime(reply.createdAt) }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, ref, type Ref } from "vue";
import { ElMessage } from "element-plus";
import { Edit, Delete } from "@element-plus/icons-vue";
import type { Editor } from "@tiptap/vue-3";
import type { CommentReply } from "../../types/comment";
import { commentActions } from "../../store/comment";
import { getRelativeTime } from "../../utils";

defineOptions({
  name: "CommentReplyItem",
});

const props = defineProps<{
  reply: CommentReply;
  commentId: string; // 所属批注ID
  currentUserId?: string; // 当前用户ID
  isResolved?: boolean; // 批注是否已解决
}>();

const emit = defineEmits<{
  (e: "reply", replyId: string, authorName: string): void; // 回复此条评论
  (e: "quote", replyId: string, authorName: string, content: string): void; // 引用回复
  (e: "quote-click", replyId: string): void; // 点击引用
  (e: "updated"): void; // 更新后事件
}>();

const editor = inject<Ref<Editor>>("editor");

const isEditing = ref(false);
const editContent = ref("");

// 获取当前用户ID（默认值，实际应该从用户系统获取）
const currentUserId = computed(() => props.currentUserId || "current-user-id");

// 判断是否可以编辑（只能编辑自己的回复，且批注未解决）
const canEdit = computed(() => {
  return (
    !props.isResolved &&
    props.reply.author.id === currentUserId.value &&
    !props.reply.isDeleted
  );
});

// 判断是否可以删除（可以删除自己的回复，管理员可以删除所有，且批注未解决）
const canDelete = computed(() => {
  if (props.isResolved || props.reply.isDeleted) return false;
  // TODO: 检查是否是管理员
  const isAdmin = false;
  return props.reply.author.id === currentUserId.value || isAdmin;
});

// 用户点赞类型
const userLikeType = computed<"like" | "dislike" | null>(() => {
  if (!props.reply.likes?.length) return null;
  const userLike = props.reply.likes.find(
    (like) => like.userId === currentUserId.value
  );
  return userLike ? userLike.type : null;
});

// 格式化时间
const formatTime = (time: string) => {
  return getRelativeTime(time);
};

// 点赞
const handleLike = () => {
  // 已解决的批注不能点赞
  if (props.isResolved || !editor?.value) return;

  const likeType = userLikeType.value;
  if (likeType === "like") {
    // 取消点赞
    commentActions.toggleReplyLike(
      props.commentId,
      props.reply.id,
      currentUserId.value,
      null,
      editor.value
    );
  } else {
    // 点赞（如果之前点踩了，则改为点赞）
    commentActions.toggleReplyLike(
      props.commentId,
      props.reply.id,
      currentUserId.value,
      "like",
      editor.value
    );
  }
  emit("updated");
};

// 点踩
const handleDislike = () => {
  // 已解决的批注不能点踩
  if (props.isResolved || !editor?.value) return;

  const likeType = userLikeType.value;
  if (likeType === "dislike") {
    // 取消点踩
    commentActions.toggleReplyLike(
      props.commentId,
      props.reply.id,
      currentUserId.value,
      null,
      editor.value
    );
  } else {
    // 点踩（如果之前点赞了，则改为点踩）
    commentActions.toggleReplyLike(
      props.commentId,
      props.reply.id,
      currentUserId.value,
      "dislike",
      editor.value
    );
  }
  emit("updated");
};

// 回复
const handleReply = () => {
  // 已解决的批注不能回复
  if (props.isResolved) return;
  emit("reply", props.reply.id, props.reply.author.name);
};

// 处理单击事件（阻止冒泡，避免触发父元素的滚动）
const handleClick = (event: MouseEvent) => {
  // 阻止事件冒泡到父元素，避免触发批注项的滚动
  event.stopPropagation();
};

// 双击引用
const handleDoubleClick = (event: MouseEvent) => {
  // 已解决的批注不能使用引用功能
  if (props.isResolved) {
    event.stopPropagation();
    return;
  }
  if (props.reply.isDeleted) return;
  
  // 检查事件目标是否为按钮或按钮的子元素，如果是则忽略（避免点击按钮时触发引用）
  const target = event.target as HTMLElement;
  if (target) {
    // 检查是否点击在按钮区域或操作区域内
    const isButton = target.closest('.el-button') || target.closest('.reply-actions');
    if (isButton) {
      event.stopPropagation();
      return;
    }
  }
  
  // 阻止事件冒泡，避免触发父元素的点击事件（导致滚动）
  event.stopPropagation();
  emit("quote", props.reply.id, props.reply.author.name, props.reply.content);
};

// 点击引用内容滚动到原评论
const handleQuoteClick = () => {
  if (!props.reply.quote) return;
  emit("quote-click", props.reply.quote.replyId);
};

// 获取纯文本内容（用于显示）
const getPlainText = (html: string) => {
  if (!html) return "";
  const div = document.createElement("div");
  div.innerHTML = html;
  return div.textContent || div.innerText || "";
};

// 编辑
const handleEdit = () => {
  // 已解决的批注不能编辑
  if (props.isResolved) return;
  isEditing.value = true;
  editContent.value = props.reply.content;
};

// 保存编辑
const handleSaveEdit = () => {
  const content = editContent.value.trim();
  if (!content) {
    ElMessage.warning("回复内容不能为空");
    return;
  }

  if (!editor?.value) return;

  commentActions.updateReply(
    props.commentId,
    props.reply.id,
    content,
    editor.value
  );

  isEditing.value = false;
  editContent.value = "";
  emit("updated");
  ElMessage.success("回复已更新");
};

// 取消编辑
const handleCancelEdit = () => {
  isEditing.value = false;
  editContent.value = "";
};

// 删除
const handleDelete = () => {
  // 已解决的批注不能删除
  if (props.isResolved || !editor?.value) return;

  commentActions.deleteReply(
    props.commentId,
    props.reply.id,
    currentUserId.value,
    editor.value
  );

  emit("updated");
  ElMessage.success("回复已删除");
};

// 处理下拉菜单命令
const handleCommand = (command: string) => {
  switch (command) {
    case "edit":
      handleEdit();
      break;
    case "delete":
      handleDelete();
      break;
  }
};
</script>

<style lang="scss" scoped>
.comment-reply-item {
  margin-bottom: 12px;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.2s ease;

  &:hover {
    background-color: var(--comment-reply-hover-background);
  }

  &.deleted {
    opacity: 0.6;
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.reply-quote-inline {
  margin-bottom: 8px;
  margin-left: 0;
  padding: 6px 10px;
  background-color: var(--comment-quote-background);
  border-radius: 4px;
  font-size: 11px;
  line-height: 1.4;
  cursor: pointer;
  transition: background-color 0.2s;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  &:hover {
    background-color: var(--comment-item-hover-background);
  }

  .quote-content {
    color: var(--comment-quote-text-color);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 11px;
  }
}

.reply-header {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
}

.reply-author-avatar-wrapper {
  flex-shrink: 0;
}

.reply-author-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
}

.reply-author-avatar-placeholder {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 12px;
  font-weight: 600;
}

.reply-author-info {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
  min-width: 0;
  flex-wrap: wrap;
}

.reply-author-name {
  font-size: 13px;
  font-weight: 600;
  color: var(--editor-text-color);
}

.reply-time-meta {
  margin-top: 4px;
  display: flex;
  align-items: center;
}

.reply-time {
  font-size: 11px;
  color: var(--comment-time-color);
}

.reply-edited-badge {
  font-size: 11px;
  color: var(--comment-time-color);
  font-style: italic;
}

.reply-actions {
  display: flex;
  align-items: center;
  gap: 0px; // 减小按钮间隔
  flex-shrink: 0;
  margin-left: auto;

  .el-button {
    padding: 2px 4px; // 减小内边距
    font-size: 12px;
    min-height: auto;
    height: auto;
    margin-left: 2px; // 使用margin控制间距

    &:first-child {
      margin-left: 0;
    }

    &.active {
      color: var(--editor-primary-color, #1890ff);
    }

    i {
      font-size: 14px;
      margin-right: 2px;
    }

    span {
      font-size: 12px;
    }
  }
}

.reply-edit-mode {
  margin-top: 8px;
  margin-left: 32px; // 与头像对齐
}

.edit-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}

.reply-content-wrapper {
  margin-top: 4px;
  margin-left: 32px; // 与头像对齐
}

.reply-content {
  font-size: 13px;
  line-height: 1.6;
  word-break: break-word;
  color: var(--editor-text-color);
  margin-bottom: 4px;

  :deep(p) {
    margin: 0 0 4px 0;
    &:last-child {
      margin-bottom: 0;
    }
  }

  :deep(ul),
  :deep(ol) {
    margin: 4px 0;
    padding-left: 20px;
  }
}

.reply-content-deleted {
  font-size: 13px;
  color: #999;
  font-style: italic;
  margin-left: 32px;
  margin-bottom: 4px; // 确保与时间有间距
}
</style>
